<script setup lang="ts">
import { unwrapApiBody, type ApiResponse } from '../../../utils/http/factory'
import { renderSafeMarkdown } from '../../../utils/render-markdown'

definePageMeta({
  layout: 'public',
})

const route = useRoute()
const slug = computed(() => route.params.publicSlug as string)

type AboutPayload = {
  user: { publicSlug: string | null; nickname: string | null; avatar: string | null }
  bio: { markdown: string }
}

const { data, pending, error } = await useAsyncData(
  () => `public-about-${slug.value}`,
  async () => {
    const res = await $fetch<ApiResponse<AboutPayload>>(
      `/api/public/profile/${encodeURIComponent(slug.value)}/about`,
    )
    return unwrapApiBody(res)
  },
  { watch: [slug] },
)

const renderedBio = computed(() => (data.value?.bio.markdown ? renderSafeMarkdown(data.value.bio.markdown) : ''))

const displayName = computed(
  () => data.value?.user.nickname || data.value?.user.publicSlug || slug.value,
)

useHead(() => ({
  title: data.value ? `${displayName.value} · 关于` : '关于',
}))
</script>

<template>
  <div v-if="pending && !data" class="text-muted py-10">
    <UContainer>加载中…</UContainer>
  </div>
  <UContainer v-else-if="error && !data" class="py-10">
    <UAlert color="error" title="无法加载页面" description="该用户没有公开的简介，或主页不存在。" />
  </UContainer>
  <UContainer v-else-if="data" class="py-10 max-w-3xl space-y-8">
    <div class="flex flex-col items-center gap-3 sm:flex-row sm:items-start">
      <img
        v-if="data.user.avatar"
        :src="data.user.avatar"
        alt=""
        class="h-20 w-20 shrink-0 rounded-full border border-default object-cover"
      >
      <div class="text-center sm:text-left">
        <h1 class="text-2xl font-semibold">
          {{ displayName }}
        </h1>
        <p class="mt-1 text-sm text-muted">
          关于
        </p>
      </div>
    </div>
    <div
      class="prose prose-neutral dark:prose-invert max-w-none prose-img:rounded-lg"
      v-html="renderedBio"
    />
    <div>
      <UButton :to="`/@${slug}`" variant="ghost" icon="i-lucide-arrow-left">
        返回主页
      </UButton>
    </div>
  </UContainer>
</template>
